package com.karaku.karaku_collector.util;

import android.content.Context;
import android.hardware.Camera;
import android.util.DisplayMetrics;
import android.view.WindowManager;

import com.karaku.karaku_collector.App;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * Created by guopi on 2017/11/3 0003.
 */

public class CameraUtil {

    private static Size bestSize;
    private static List<Size> cameraSizes;

    public static List<Size> getCameraSizes() {
        if (cameraSizes == null) {
            Camera c = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);
            List<Camera.Size> ss = c.getParameters().getSupportedPreviewSizes();
            List<Size> r = new ArrayList<>();
            Size screenSize = getScreenSize();
            for (Camera.Size s : ss) {
                if (s.height >= screenSize.width && s.width * 1.f / s.height <= screenSize.height * 1.f / screenSize.width) {
                    r.add(new Size(s.width, s.height));
                }
            }
            c.stopPreview();
            c.setPreviewCallback(null);
            c.release();
            Collections.sort(r, new Comparator<Size>() {
                @Override
                public int compare(Size o1, Size o2) {
                    float r1 = o1.height * 1.f / o1.width;
                    float r2 = o2.height * 1.f / o2.width;
                    if (r1 > r2) {
                        return 1;
                    } else if (r1 < r2) {
                        return -1;
                    } else {
                        return 0;
                    }
                }
            });
            cameraSizes = r;
        }
        return cameraSizes;
    }

    public static Size getBestCameraSize() {
        if (bestSize == null) {
            try {
                boolean b = false;
                Size find = null;
                for (Size s : getCameraSizes()) {
                    if (Math.abs(s.width * 1.f / s.height - 1.33f) < 0.01f) {
                        LogUtil.d("CAMERA", "find best size===");
                        find = s;
                    }
                    if (s.width == 1920 && s.height == 1440) {
                        b = true;
                        break;
                    }
                }
                if (b) {
                    bestSize = new Size(1920, 1440);
                } else {
                    bestSize = find;
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return bestSize;
    }

    public static Size getScreenSize() {
        WindowManager manager = (WindowManager) App.getInstance().getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(outMetrics);
        return new Size(outMetrics.widthPixels, outMetrics.heightPixels);
    }
}
